package com.block.channel.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.channel.service.IChannelBaseInfoService;
import com.block.channel.service.IChannelCountInfoService;
import com.block.channel.service.IChannelCountUvInfoService;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.enums.ChargeTypeEnum;
import com.block.common.model.dto.CountInfoDTO;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.common.util.IpUtil;
import com.block.common.util.LocalDateUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.ChannelBaseInfo;
import com.block.db.mapper.ChannelBaseInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 渠道基本信息表 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-09-01
 */
@Service
public class ChannelBaseInfoServiceImpl extends ServiceImpl<ChannelBaseInfoMapper, ChannelBaseInfo> implements IChannelBaseInfoService {

    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    IChannelCountUvInfoService channelCountUvInfoService;
    @Autowired
    IChannelCountInfoService channelCountInfoService;

    /**
     * uv 统计 处理
     */
    @Override
    public String channelUvHandle(ChannelBaseInfo channelBaseInfo, HttpServletRequest request){

        String reqIp = IpUtil.getIp(request);
        String randomId = UUID.randomUUID().toString(true);
        String channelCode = channelBaseInfo.getChannelCode();

        // 获取落地页类型
        Long remainSecond = LocalDateUtil.getRemainSecondNumber();
        String redisKey = StrUtil.format(RedisKeyConstant.COUNT_UV_KEY, channelCode, reqIp);
        boolean result = stringRedisTemplate.opsForValue()
                .setIfAbsent(redisKey, System.currentTimeMillis()+"",remainSecond, TimeUnit.SECONDS);

        if (result){

            String userAgent = request.getHeader("User-Agent");
            channelCountInfoService.countChannelUvDataInfo(channelBaseInfo, reqIp, userAgent, randomId);
        }

        // TODO: 2023/9/1 mongodb 大量数据统计
        ApplicationInfo applicationInfo = applicationInfoService.getAppInfoByAppCode(channelBaseInfo.getAppCode());
        String viewUrl = applicationInfo.getH5Url() + "?ch=" + channelCode + "&randomUuid="+ randomId;
        return viewUrl;
    }

}
